package com.ymm.service.impl;

import com.ymm.domain.entity.MailSendInfo;
import com.ymm.domain.vo.ResponseResult;
import com.ymm.enums.AppHttpCodeEnum;
import com.ymm.enums.RedisKeyEnum;
import com.ymm.exception.SystemException;
import com.ymm.service.EmailService;
import com.ymm.utils.RedisCache;
import com.ymm.utils.VerifyCodeUtils;
import com.ymm.utils.email.EmailValidator;
import com.ymm.utils.email.MailSander;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 椰咩咩咩
 * @version 1.0-SNAPSHOT
 * @date 2023/1/31 20:55
 * @Description
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private MailSendInfo mailSendInfo;

    @Resource
    private MailSander mailSander;

    @Resource
    private RedisCache redisCache;

    /**
     * 发送验证码
     *
     * @param address
     * @return
     */
    @Override
    public ResponseResult sendCkCode(String address) {
        if (!StringUtils.hasText(address)) {
            throw new SystemException(AppHttpCodeEnum.REQUIRE_EMAIL_ADDRESS);
        }
        if (!EmailValidator.isValidEmail(address)) {
            throw new SystemException(AppHttpCodeEnum.INVALID_EMAIL);
        }
        // 指定验证码的字符源为纯数字
        String source = "0123456789";
        //生成验证码
        String checkCode = VerifyCodeUtils.generateVerifyCode(6, source);
        String checkCodeKey = RedisKeyEnum.HT_MAIL_KEY + address;
        //检查验证码是否已经在60s内发送过
        if (StringUtils.hasText(redisCache.getCacheObject(RedisKeyEnum.HT_MAIL_STATUS + address))) {
            throw new SystemException(AppHttpCodeEnum.CHECK_CODE_OUT_TIME);
        }
        //将验证码存放在Redis里面
        redisCache.setCacheObject(checkCodeKey, checkCode, 60 * 10, TimeUnit.SECONDS);
        //redis存储用户发送验证码的状态
        redisCache.setCacheObject(RedisKeyEnum.HT_MAIL_STATUS + address, checkCode, 60, TimeUnit.SECONDS);
        //添加邮件发送的信息
        mailSendInfo.setSubject("椰咩咩大学生健康管理系统验证码");
        mailSendInfo.setContent("<b>【椰咩咩大学生健康管理系统】</b>" +
                "<br>您当前的验证码为<b>" + checkCode + "</b>" +
                "<br>此验证码仅用于椰咩咩大学生健康管理系统安全管理服务平台的验证，请勿转发。<br>" +
                "如非本人操作，请忽略本条邮件<br>请在10分钟内使用验证码");
        List<String> addresses = new ArrayList<>();
        addresses.add(address);
        mailSendInfo.setToAddresses(addresses);
        //发送邮件
        mailSander.sendMail(mailSendInfo);
        return ResponseResult.okResult();
    }

}
